import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import css from 'rollup-plugin-css-porter';
import { terser } from 'rollup-plugin-terser';
import { build } from 'vite';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const componentsDir = path.resolve(__dirname, 'src/components');
const files = getAllVueFiles(componentsDir);

async function buildComponents() {
  for (const file of files) {
    const relativePath = path.relative(__dirname, file);
    const name = path.relative(componentsDir, relativePath).replace(/\\/g, '/').replace(/\.vue$/, '');
    const computedArr = name.split("/");
    computedArr.pop();

    // 此处需要将除去runtime/design-time/props-panel下的原始vue文件的其他文件不允许打包，只做填充
    if(computedArr.length > 2){ continue }

    const component = {
      // 打包文件路径
      input: relativePath,
      // 文件名称
      fileName: path.basename(relativePath, '.vue') + '.js',
      // 组件名称
      name: path.basename(relativePath, '.vue'),
      // 打包路径
      outDir: path.resolve(__dirname, 'dist', 'components', computedArr.join("/")),
    };
    
    // 确保输出目录存在
    // fs.mkdirSync(component.outDir, { recursive: true });

    await build({
      build: {
        lib: {
          entry: component.input,
          name: component.name,
          fileName: () => component.fileName,
          // 当前打包模式，只有iife模式可以被浏览器识别
          formats: ['iife'],
        },
        outDir: component.outDir,
        rollupOptions: {
          plugins: [
            // 使用 rollup-plugin-css-only 来处理 CSS
            css({
              // 输出选项
              output: (styles, styleNodes) => {
                // 将 CSS 内联到 JavaScript 中
                return `export default ${JSON.stringify(styles)};`;
              },
            }),
            terser()
          ],
          output: {
            format: 'iife',
            globals: {
              vue: 'Vue',
            },
          },
        },
      },
    });

    // 需要将当前component.json文件拷贝到dist目录下对应组件的同级目录下
    if(relativePath.includes('runtime')){
      const componentJsonPath = path.resolve(__dirname, 'src', 'components', computedArr[0],'component.json');
      const componentJsonDistPath = path.resolve(__dirname, 'dist', 'components', computedArr[0], 'component.json');
      fs.copyFileSync(componentJsonPath, componentJsonDistPath);
    }

    // 删除每个文件下面的vite.svg文件，这是由于调用vite.build方法会自动默认将public目录下的文件原样输出到根路径下面
    const viteSvgPath = path.resolve(__dirname, 'dist', 'components', computedArr.join("/"), 'vite.svg');
    fs.unlinkSync(viteSvgPath);
  }

  // 拷贝整个src目录下的文件到dist目录下
  copySrcFileToDist();

  // 拷贝manifest.json文件到dist目录下
  const manifestPath = path.resolve(__dirname,'manifest.json');
  const manifestDistPath = path.resolve(__dirname, 'dist','manifest.json');
  fs.copyFileSync(manifestPath, manifestDistPath);

  // 拷贝package.json文件到dist目录下
  const packageJsonPath = path.resolve(__dirname,'package.json');
  const packageJsonDistPath = path.resolve(__dirname, 'dist','package.json');
  fs.copyFileSync(packageJsonPath, packageJsonDistPath);

}

function copyDir(source, destination) {
  fs.mkdirSync(destination, { recursive: true });
  fs.readdirSync(source).forEach(file => {
    const sourcePath = path.join(source, file);
    const destinationPath = path.join(destination, file);

    if (fs.lstatSync(sourcePath).isDirectory()) {
      copyDir(sourcePath, destinationPath);
    } else {
      fs.copyFileSync(sourcePath, destinationPath);
    }
  });
}

/**
 * 拷贝整个src目录下的文件到dist目录下
 */
const copySrcFileToDist = () => {
  const source = 'src';
  const destination = 'dist/src';
  try {
    copyDir(source, destination);
    console.log(`拷贝src目录成功`);
  } catch (err) {
    console.error("拷贝src目录失败");
  }
}


function getAllVueFiles(dir) {
  let files = [];
  const items = fs.readdirSync(dir);

  for (const item of items) {
    const itemPath = path.join(dir, item);
    const stat = fs.statSync(itemPath);

    if (stat.isDirectory()) {
      files = files.concat(getAllVueFiles(itemPath));
    } else if (item.endsWith('.vue')) {
      files.push(itemPath);
    }
  }

  return files;
}

buildComponents().then(() => {
  console.log('All components have been built successfully.');
}).catch(error => {
  console.error('Error building components:', error);
});